<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>http | 个人博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210">
<meta property="og:type" content="article">
<meta property="og:title" content="http">
<meta property="og:url" content="https://gitee.com/wieldy/bailment-blog/2022/03/29/http%E6%89%8B%E5%86%99/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2022-03-29T14:12:00.000Z">
<meta property="article:modified_time" content="2023-04-23T12:11:43.651Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/bailment-blog/atom.xml" title="个人博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/bailment-blog/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/bailment-blog/css/style.css">

  
    
<link rel="stylesheet" href="/bailment-blog/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/bailment-blog/" id="logo">个人博客</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/bailment-blog/">Home</a>
        
          <a class="main-nav-link" href="/bailment-blog/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/bailment-blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/wieldy/bailment-blog"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-http手写" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/http%E6%89%8B%E5%86%99/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      http
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>).<span class="property">promises</span>;</span><br><span class="line"><span class="keyword">const</span> &#123; createReadStream &#125; = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> zlib = <span class="built_in">require</span>(<span class="string">&#x27;zlib&#x27;</span>)</span><br><span class="line"><span class="comment">// const url = require(&#x27;url&#x27;); // req.url 有 query</span></span><br><span class="line"><span class="keyword">const</span> os = <span class="built_in">require</span>(<span class="string">&#x27;os&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> querystring = <span class="built_in">require</span>(<span class="string">&#x27;querystring&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// --------------------------</span></span><br><span class="line"><span class="keyword">const</span> chalk = <span class="built_in">require</span>(<span class="string">&#x27;chalk&#x27;</span>); <span class="comment">// 粉笔 可以展现不同的颜色</span></span><br><span class="line"><span class="keyword">const</span> parse = <span class="built_in">require</span>(<span class="string">&#x27;url-parse&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> debug = <span class="built_in">require</span>(<span class="string">&#x27;debug&#x27;</span>)(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> mime = <span class="built_in">require</span>(<span class="string">&#x27;mime&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> ejs = <span class="built_in">require</span>(<span class="string">&#x27;ejs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 多语言 语言表</span></span><br><span class="line"><span class="keyword">const</span> messages = &#123;</span><br><span class="line">    <span class="attr">en</span>: <span class="string">&#x27;hello world&#x27;</span>,</span><br><span class="line">    <span class="attr">ja</span>: <span class="string">&#x27;こんにちは、世界&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 就是两个网站 通过url来区分 是什么语言 /zh-CN  /en</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Server</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">options = &#123;&#125;</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">port</span> = options.<span class="property">port</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">directory</span> = options.<span class="property">directory</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">address</span> = options.<span class="property">address</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">start</span>();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">processReqData</span>(<span class="params">req</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">const</span> arr = [];</span><br><span class="line">            req.<span class="title function_">on</span>(<span class="string">&#x27;data&#x27;</span>, <span class="keyword">function</span> (<span class="params">chunk</span>) &#123;</span><br><span class="line">                arr.<span class="title function_">push</span>(chunk);</span><br><span class="line">            &#125;);</span><br><span class="line">            req.<span class="title function_">on</span>(<span class="string">&#x27;end&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">                <span class="comment">// 客户端告诉服务器如何解析数据</span></span><br><span class="line">                <span class="keyword">let</span> data = <span class="title class_">Buffer</span>.<span class="title function_">concat</span>(arr).<span class="title function_">toString</span>();</span><br><span class="line">                <span class="keyword">let</span> contentType = req.<span class="property">headers</span>[<span class="string">&#x27;content-type&#x27;</span>];</span><br><span class="line">                <span class="keyword">if</span> (contentType === <span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>) &#123;</span><br><span class="line">                    <span class="comment">// a=b&amp;c=d  =&gt; &#123;a:b,c:d&#125;  qs</span></span><br><span class="line">                    <span class="title function_">resolve</span>(querystring.<span class="title function_">parse</span>(data))</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (contentType === <span class="string">&#x27;application/json&#x27;</span>) &#123;</span><br><span class="line">                    <span class="title function_">resolve</span>(<span class="title class_">JSON</span>.<span class="title function_">parse</span>(data))</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="title function_">resolve</span>(&#123;&#125;)</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">async</span> <span class="title function_">request</span>(<span class="params">pathname, query, req, res</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> mock = path.<span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">directory</span>, <span class="string">&#x27;mock.js&#x27;</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">await</span> fs.<span class="title function_">stat</span>(mock);</span><br><span class="line">            req.<span class="property">body</span> = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="title function_">processReqData</span>(req); <span class="comment">// 请求体的数据</span></span><br><span class="line">            req.<span class="property">query</span> = query;</span><br><span class="line">            <span class="keyword">let</span> mockFn = <span class="built_in">require</span>(mock)</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">mockFn</span>(pathname, req, res)</span><br><span class="line">        &#125; <span class="keyword">catch</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    handleRequest = <span class="keyword">async</span> (req, res) =&gt; &#123; <span class="comment">// 处理客户端的请求  和响应客户端</span></span><br><span class="line">        <span class="comment">// 获取用户的路径 </span></span><br><span class="line">        <span class="keyword">let</span> &#123; pathname, query &#125; = <span class="title function_">parse</span>(req.<span class="property">url</span>, <span class="literal">true</span>)</span><br><span class="line">        <span class="comment">// cors</span></span><br><span class="line">        <span class="keyword">if</span> (req.<span class="property">headers</span>.<span class="property">origin</span>) &#123; <span class="comment">// 可以看origin值是否有值，有值则是出现了跨域问题</span></span><br><span class="line">            res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>, req.<span class="property">headers</span>.<span class="property">origin</span>); <span class="comment">// 写*在有cookie的情况是不可以的</span></span><br><span class="line">            res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="string">&#x27;authorization&#x27;</span>)</span><br><span class="line">            res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Max-Age&#x27;</span>, <span class="string">&#x27;10&#x27;</span>); <span class="comment">// 10才发一次options get/post + 自定义header  发送的请求不是get或者post</span></span><br><span class="line">            res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Allow-Methods&#x27;</span>, <span class="string">&#x27;GET,POST,PUT,DELETE,OPTIONS&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (req.<span class="property">method</span> === <span class="string">&#x27;OPTIONS&#x27;</span>) &#123; <span class="comment">// 服务端遇到options 返回ok即可</span></span><br><span class="line">            <span class="keyword">return</span> res.<span class="title function_">end</span>();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> flag = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="title function_">request</span>(pathname, query, req, res)</span><br><span class="line">        <span class="keyword">if</span> (flag) &#123;</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 根据目录读取  mock数据 </span></span><br><span class="line">        <span class="keyword">if</span> (pathname === <span class="string">&#x27;/hello&#x27;</span>) &#123; <span class="comment">// 实现多语言</span></span><br><span class="line">            <span class="keyword">let</span> lans = req.<span class="property">headers</span>[<span class="string">&#x27;accept-language&#x27;</span>];</span><br><span class="line">            <span class="comment">// zh-CN,zh;q=0.9,es;q=0.8 </span></span><br><span class="line">            <span class="keyword">const</span> langObj = lans.<span class="title function_">split</span>(<span class="string">&#x27;,&#x27;</span>).<span class="title function_">map</span>(<span class="function"><span class="params">lan</span> =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">let</span> [name, q = <span class="string">&#x27;q=1&#x27;</span>] = lan.<span class="title function_">split</span>(<span class="string">&#x27;;&#x27;</span>);</span><br><span class="line">                <span class="keyword">return</span> &#123; name, <span class="attr">q</span>: q.<span class="title function_">split</span>(<span class="string">&#x27;=&#x27;</span>)[<span class="number">1</span>] &#125;;</span><br><span class="line">            &#125;).<span class="title function_">sort</span>(<span class="function">(<span class="params">a, b</span>) =&gt;</span> b.<span class="property">q</span> - a.<span class="property">q</span>)</span><br><span class="line"></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; langObj.<span class="property">length</span>; i++) &#123;</span><br><span class="line">                <span class="keyword">let</span> lan = messages[langObj[i].<span class="property">name</span>];</span><br><span class="line">                <span class="keyword">if</span> (lan) &#123;</span><br><span class="line">                    <span class="keyword">return</span> res.<span class="title function_">end</span>(lan);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> res.<span class="title function_">end</span>(messages[<span class="string">&#x27;en&#x27;</span>])</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// referer的处理 有些图片只能在我的域名下访问，不能被别人的网站去访问。 防盗链</span></span><br><span class="line">        <span class="comment">// referer || referrer  两个都支持一下</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="regexp">/\.(webp)/</span>.<span class="title function_">test</span>(pathname)) &#123;</span><br><span class="line">            <span class="keyword">let</span> referer = req.<span class="property">headers</span>[<span class="string">&#x27;referer&#x27;</span>] || req.<span class="property">headers</span>[<span class="string">&#x27;referrer&#x27;</span>];</span><br><span class="line">            <span class="keyword">let</span> whiteList = []</span><br><span class="line">            <span class="keyword">if</span> (referer) &#123; <span class="comment">// 说明有人引用我的资源了， 我需要检验一下</span></span><br><span class="line">                <span class="keyword">let</span> hostname = <span class="string">&#x27;http://&#x27;</span> + req.<span class="property">headers</span>[<span class="string">&#x27;host&#x27;</span>];</span><br><span class="line">                <span class="keyword">let</span> a1 = <span class="title function_">parse</span>(hostname).<span class="property">hostname</span>;</span><br><span class="line">                <span class="keyword">let</span> a2 = <span class="title function_">parse</span>(referer).<span class="property">hostname</span>;</span><br><span class="line">                <span class="keyword">if</span> (a1 !== a2 || whiteList.<span class="title function_">includes</span>(<span class="string">&#x27;xxx&#x27;</span>)) &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="title function_">createReadStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;error.webp&#x27;</span>)).<span class="title function_">pipe</span>(res);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 静态服务----------------------------------------</span></span><br><span class="line">            <span class="keyword">let</span> queryPath = path.<span class="title function_">join</span>(<span class="variable language_">this</span>.<span class="property">directory</span>, pathname);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">let</span> statObj = <span class="keyword">await</span> fs.<span class="title function_">stat</span>(queryPath);</span><br><span class="line">            <span class="keyword">if</span> (statObj.<span class="title function_">isFile</span>()) &#123;</span><br><span class="line">                <span class="variable language_">this</span>.<span class="title function_">sendFile</span>(queryPath, req, res, statObj)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 根据路径读取路径对应的目录</span></span><br><span class="line">                <span class="keyword">let</span> dirs = <span class="keyword">await</span> fs.<span class="title function_">readdir</span>(queryPath);</span><br><span class="line">                <span class="keyword">let</span> fileStatus = <span class="keyword">await</span> <span class="title class_">Promise</span>.<span class="title function_">all</span>(dirs.<span class="title function_">map</span>(<span class="keyword">async</span> dir =&gt; <span class="keyword">await</span> fs.<span class="title function_">stat</span>(path.<span class="title function_">join</span>(queryPath, dir))));</span><br><span class="line">                dirs = dirs.<span class="title function_">map</span>(<span class="function">(<span class="params">dir, index</span>) =&gt;</span> &#123;</span><br><span class="line">                    <span class="keyword">return</span> &#123;</span><br><span class="line">                        <span class="attr">url</span>: path.<span class="title function_">join</span>(pathname, dir),</span><br><span class="line">                        dir,</span><br><span class="line">                        <span class="attr">info</span>: fileStatus[index].<span class="title function_">isFile</span>() ? <span class="string">&#x27;文件&#x27;</span> : <span class="string">&#x27;文件夹&#x27;</span>,</span><br><span class="line">                        <span class="attr">size</span>: fileStatus[index].<span class="property">size</span> == <span class="number">0</span> ? <span class="string">&#x27;&#x27;</span> : fileStatus[index].<span class="property">size</span></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">                <span class="comment">// 可以使用模板引擎来进行数据渲染 ejs  handlerbar jade nunjucks underscore</span></span><br><span class="line">                <span class="keyword">let</span> html = <span class="keyword">await</span> ejs.<span class="title function_">renderFile</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;./template.html&#x27;</span>), &#123; dirs &#125;);</span><br><span class="line">                res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;text/html;charset=utf-8&#x27;</span>)</span><br><span class="line">                res.<span class="title function_">end</span>(html);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">sendError</span>(e, res)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">cache</span>(<span class="params">queryPath, statObj, req, res</span>) &#123;</span><br><span class="line">        <span class="comment">// 默认5s内 不像服务端发送请求 </span></span><br><span class="line">        res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Cache-Control&#x27;</span>, <span class="string">&#x27;max-age=5&#x27;</span>); <span class="comment">// 5s 内不再发送请求</span></span><br><span class="line">        <span class="keyword">let</span> etag = statObj.<span class="property">size</span> + <span class="string">&#x27;-&#x27;</span> + statObj.<span class="property">ctime</span>.<span class="title function_">getTime</span>();</span><br><span class="line">        res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Etag&#x27;</span>, etag); <span class="comment">// 设置etag</span></span><br><span class="line">        <span class="keyword">let</span> ifNoneMatch = req.<span class="property">headers</span>[<span class="string">&#x27;if-none-match&#x27;</span>];</span><br><span class="line">        <span class="keyword">if</span> (ifNoneMatch == etag) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">gzip</span>(<span class="params">queryPath, req, res</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!<span class="regexp">/\.(css|js|txt|html)/</span>.<span class="title function_">test</span>(queryPath)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>; <span class="comment">// 不是html这些类型 不进行压缩处理</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 内容协商</span></span><br><span class="line">        <span class="keyword">let</span> encoding = req.<span class="property">headers</span>[<span class="string">&#x27;accept-encoding&#x27;</span>]; <span class="comment">// 浏览器自己加的 </span></span><br><span class="line">        <span class="keyword">if</span> (encoding.<span class="title function_">includes</span>(<span class="string">&#x27;gzip&#x27;</span>)) &#123;</span><br><span class="line">            res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Encoding&#x27;</span>, <span class="string">&#x27;gzip&#x27;</span>); <span class="comment">// 告诉浏览器用什么方式来进行解析</span></span><br><span class="line">            <span class="keyword">return</span> zlib.<span class="title function_">createGzip</span>();  <span class="comment">// zlib.createDeflate  zlib.createBrotliCompress</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">sendFile</span>(<span class="params">queryPath, req, res, statObj</span>) &#123; <span class="comment">// 根据路径创建一个可读流.pipe(res)</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="title function_">cache</span>(queryPath, statObj, req, res)) &#123;</span><br><span class="line">            res.<span class="property">statusCode</span> = <span class="number">304</span>;</span><br><span class="line">            res.<span class="title function_">end</span>()</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 没有缓存就考虑压缩</span></span><br><span class="line">        <span class="keyword">let</span> createGzip;</span><br><span class="line">        res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, mime.<span class="title function_">getType</span>(queryPath) + <span class="string">&#x27;;charset=utf-8&#x27;</span>)</span><br><span class="line">        <span class="keyword">if</span> (createGzip = <span class="variable language_">this</span>.<span class="title function_">gzip</span>(queryPath, req, res)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">createReadStream</span>(queryPath).<span class="title function_">pipe</span>(createGzip).<span class="title function_">pipe</span>(res);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="title function_">createReadStream</span>(queryPath).<span class="title function_">pipe</span>(res);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">sendError</span>(<span class="params">e, res</span>) &#123;</span><br><span class="line">        <span class="comment">// 能根据不同的环境 打印出日志来</span></span><br><span class="line">        <span class="title function_">debug</span>(e);</span><br><span class="line">        res.<span class="title function_">end</span>(<span class="string">&#x27;Not found&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">start</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> server = http.<span class="title function_">createServer</span>(<span class="variable language_">this</span>.<span class="property">handleRequest</span>);</span><br><span class="line">        <span class="keyword">const</span> port = <span class="variable language_">this</span>.<span class="property">port</span>;</span><br><span class="line">        <span class="keyword">const</span> address = <span class="variable language_">this</span>.<span class="property">address</span>.<span class="title function_">map</span>(<span class="function"><span class="params">item</span> =&gt;</span> <span class="string">&#x27;  http://&#x27;</span> + item + <span class="string">&quot;:&quot;</span> + chalk.<span class="title function_">green</span>(port))</span><br><span class="line">        server.<span class="title function_">listen</span>(port, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(chalk.<span class="title function_">yellow</span>(<span class="string">&#x27;Available on:&#x27;</span>))</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(address.<span class="title function_">join</span>(<span class="string">&#x27;\r\n&#x27;</span>));</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`Hit CTRL-C to stop the server`</span>)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="keyword">function</span> <span class="title function_">createServer</span>(<span class="params">userConfig</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> interface = os.<span class="title function_">networkInterfaces</span>(); <span class="comment">// 用户接口 </span></span><br><span class="line">    <span class="keyword">const</span> address = <span class="title class_">Object</span>.<span class="title function_">values</span>(interface).<span class="title function_">flat</span>(<span class="number">1</span>).<span class="title function_">filter</span>(<span class="function"><span class="params">item</span> =&gt;</span> item.<span class="property">family</span> === <span class="string">&#x27;IPv4&#x27;</span>).<span class="title function_">map</span>(<span class="function"><span class="params">item</span> =&gt;</span> item.<span class="property">address</span>)</span><br><span class="line">    userConfig[<span class="string">&#x27;address&#x27;</span>] = address</span><br><span class="line">    <span class="comment">// 这里可以对userConfig进行二次处理，处理后使用配置创建服务</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Server</span>(userConfig);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// // 设置强制缓存 不用每一次都请求了 10s内不要在来访问css</span></span><br><span class="line"><span class="comment">//         // res.setHeader(&#x27;Expires&#x27;, new Date(Date.now() + 10 * 1000).toGMTString()); // http1.0</span></span><br><span class="line"><span class="comment">//         // no-cache 不利用缓存 但是缓存了  /  no-store  压根没有缓存</span></span><br><span class="line"><span class="comment">//         res.setHeader(&#x27;Cache-Control&#x27;, &#x27;max-age=0&#x27;); // 10s 内你找浏览器的本地缓存就可以了</span></span><br><span class="line"><span class="comment">//         // 只有引用的资源 才能走强制缓存，默认直接访问的资源不能强制缓存</span></span><br><span class="line"><span class="comment">//         // 首次访问的资源会默认添加 max-age=0 不走强制缓存</span></span><br><span class="line"><span class="comment">//         // 不轻易更改的可以采用强制缓存</span></span><br><span class="line"><span class="comment">//         // 协商缓存  不是直接就不访问了 而是询问一下服务器要不要走缓存</span></span><br><span class="line"><span class="comment">//         let ctime = statObj.ctime.getTime(); // changeTime;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//         // 服务端设置的是last-modified  客户端下一次请求的时候会携带一个if-modified-since</span></span><br><span class="line"><span class="comment">//         // 我可以比较两个时间，如果时间一致 则说明文件没有变化 给状态码304 ，此时浏览器就会找缓存</span></span><br><span class="line"><span class="comment">//         // res.setHeader(&#x27;Last-Modified&#x27;, ctime);</span></span><br><span class="line"><span class="comment">//         // let ifModifiedSince = req.headers[&#x27;if-modified-since&#x27;]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//         // if (ifModifiedSince === ctime) &#123;</span></span><br><span class="line"><span class="comment">//         //     res.statusCode = 304; // 静态文件走nginx  nginx中会配置缓存相关的内容</span></span><br><span class="line"><span class="comment">//         //     res.end(); // 不返回文件，用你的就可以了</span></span><br><span class="line"><span class="comment">//         //     return;</span></span><br><span class="line"><span class="comment">//         // &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//         // 你的修改时间精确到了秒   1s内多次修改是监控不到的  可能两个文件一起创建出来的 ，但是内容不一样</span></span><br><span class="line"><span class="comment">//         // 宁可错杀 也不能错放 如果内容不一样 就应该用最新的 就算修改时间一样也应该用最新的</span></span><br><span class="line"><span class="comment">//         // “比较文件的内容”   内容的比较特别浪费性能， 采用折中的方案   修改时间+文件大小来生成一个标识</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//         let etag = statObj.size + &#x27;-&#x27; + ctime;</span></span><br><span class="line"><span class="comment">//         res.setHeader(&#x27;Etag&#x27;, etag);</span></span><br><span class="line"><span class="comment">//         let ifNoneMatch = req.headers[&#x27;if-none-match&#x27;]</span></span><br><span class="line"><span class="comment">//         if (ifNoneMatch === etag) &#123;</span></span><br><span class="line"><span class="comment">//             res.statusCode = 304; // 静态文件走nginx  nginx中会配置缓存相关的内容</span></span><br><span class="line"><span class="comment">//             res.end(); // 不返回文件，用你的就可以了</span></span><br><span class="line"><span class="comment">//             return;</span></span><br><span class="line"><span class="comment">//         &#125;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;%dirs.<span class="title function_">forEach</span>(<span class="function"><span class="params">item</span>=&gt;</span>&#123;%&gt;</span><br><span class="line">        <span class="language-xml"><span class="tag">&lt;<span class="name">li</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">            &lt;%=item.info%&gt;</span></span><br><span class="line"><span class="language-xml">                <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">&quot;&lt;%=item.url%&gt;&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">                    &lt;%=item.dir%&gt;</span></span><br><span class="line"><span class="language-xml">                <span class="tag">&lt;/<span class="name">a</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"></span></span><br><span class="line"><span class="language-xml">                &lt;%if(item.size)&#123;%&gt;</span></span><br><span class="line"><span class="language-xml">                    (&lt;%=item.size%&gt;b)</span></span><br><span class="line"><span class="language-xml">                        &lt;%&#125; %&gt;</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span></span><br><span class="line">        &lt;%&#125;)%&gt;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// bin/config.js</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">    <span class="string">&#x27;port&#x27;</span>: &#123;</span><br><span class="line">        <span class="attr">option</span>: <span class="string">&#x27;-p, --port &lt;port&gt;&#x27;</span>,</span><br><span class="line">        <span class="attr">description</span>: <span class="string">&#x27;Port to use. If 0, look for open port. [8080]&#x27;</span>,</span><br><span class="line">        <span class="attr">default</span>: <span class="number">8080</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&#x27;directory&#x27;</span>: &#123;</span><br><span class="line">        <span class="attr">option</span>: <span class="string">&#x27;-d, --directory &lt;dir&gt;&#x27;</span>,</span><br><span class="line">        <span class="attr">description</span>: <span class="string">&#x27;Show directory listings [true]&#x27;</span>,</span><br><span class="line">        <span class="attr">default</span>: process.<span class="title function_">cwd</span>()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// bin/www.js</span></span><br><span class="line">#! <span class="regexp">/usr/</span>bin/env node</span><br><span class="line"></span><br><span class="line"><span class="comment">// 解析用户提供的参数</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> &#123; program &#125; = <span class="built_in">require</span>(<span class="string">&#x27;commander&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> pkg = <span class="built_in">require</span>(<span class="string">&#x27;../package.json&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> config = <span class="built_in">require</span>(<span class="string">&#x27;./config&#x27;</span>)</span><br><span class="line">program</span><br><span class="line">    .<span class="title function_">name</span>(<span class="string">&quot;hs&quot;</span>)</span><br><span class="line">    .<span class="title function_">usage</span>(<span class="string">&quot;[options]&quot;</span>)</span><br><span class="line">    .<span class="title function_">version</span>(pkg.<span class="property">version</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> defaultValue = &#123;&#125;</span><br><span class="line"><span class="title class_">Object</span>.<span class="title function_">entries</span>(config).<span class="title function_">forEach</span>(<span class="function">(<span class="params">[key, &#123; option, description, <span class="keyword">default</span>: v &#125;]</span>) =&gt;</span> &#123;</span><br><span class="line">    defaultValue[key] = v</span><br><span class="line">    program</span><br><span class="line">        .<span class="title function_">option</span>(option, description)</span><br><span class="line">&#125;)</span><br><span class="line">program.<span class="title function_">parse</span>(process.<span class="property">argv</span>);</span><br><span class="line"><span class="keyword">const</span> options = program.<span class="title function_">opts</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> userConfig = <span class="title class_">Object</span>.<span class="title function_">assign</span>(defaultValue, options);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建服务将参数传递到函数中</span></span><br><span class="line"><span class="keyword">const</span> createServer = <span class="built_in">require</span>(<span class="string">&#x27;../src/server.js&#x27;</span>);</span><br><span class="line"><span class="title function_">createServer</span>(userConfig)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/http%E6%89%8B%E5%86%99/" data-id="cljmgj1ex000hzc9j2xn53o7w" data-title="http" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/bailment-blog/2022/03/29/http/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          http
        
      </div>
    </a>
  
  
    <a href="/bailment-blog/2022/03/29/module/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">module</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/07/">July 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/06/">June 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/04/">April 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/03/">March 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2022/03/">March 2022</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/bailment-blog/2023/07/03/%E5%B7%A5%E4%BD%9C%E6%97%A5%E5%BF%97/">工作日志</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/29/payMent/">payMent</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/20/%E7%BD%91%E7%BA%A2%E9%9D%A2%E8%AF%95%E9%A2%98/">原理题</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/19/%E5%89%8D%E7%AB%AF%E5%A4%A7%E5%B1%8F%E8%87%AA%E9%80%82%E5%BA%94%E6%96%B9%E6%B3%95/">前端大屏自适应方法</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/17/10%E4%B8%AAJavaScript%E5%B8%B8%E8%A7%81%E9%AB%98%E7%BA%A7%E7%9F%A5%E8%AF%86%E7%82%B9/">10个JavaScript常见高级知识点</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 John Doe<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/bailment-blog/" class="mobile-nav-link">Home</a>
  
    <a href="/bailment-blog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/bailment-blog/js/jquery-3.4.1.min.js"></script>



  
<script src="/bailment-blog/fancybox/jquery.fancybox.min.js"></script>




<script src="/bailment-blog/js/script.js"></script>





  </div>
</body>
</html>